var express = require('express');
var router = express.Router();
const query = require("../util/db.js")
const R = require("../util/resultJson.js")
const md5 = require("md5")
const uuid = require("uuid")

/*跳转登录页*/
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
/*执行登录*/
router.post("/login",function (req,res) {
  /*获取用户名和密码*/
  const {username,password} = req.body;
  /*登录SQL*/
  let sql = "select * from userinfo where username = ? and password = ?";
  /*初始化占位符数组*/
  const objs = [username,md5(password)];
  query(sql,objs).then(data=>{
    if(data.length === 0){
      res.json(R.error("用户名或密码不正确！"))
    }else{
      const userinfo = data[0];
      if(userinfo.status === 1){
        /*获取token*/
        const token = md5(uuid.v4());
        /*设置token有效期*/
        const expire = new Date();
        expire.setHours(expire.getHours()+4);
        /*获取当前登录用户编号*/
        const userId = userinfo.id;
        /*查看当前用户是否登录
        * 存在则修改否则添加
        * */
        sql = "select * from user_login where user_id = ?";
        query(sql,[userId]).then(data=>{
          if(data.length === 0){
            sql = "insert into user_login values(null,?,?,?)";
            query(sql,[userId,token,expire]).then(r=>{
              /*解决cookie时区问题*/
              expire.setHours(expire.getHours()+8)
              /*设置token存入cookie*/
              res.cookie("token",token,{expires:expire})
              if(r>0){
                res.json(R.success());
              }else{
                res.json(R.error("token失效！"))
              }
            });
          }else{
            sql = "update user_login set token = ?,expire = ? where id = ?";
            query(sql,[token,expire,data[0].id]).then(r=>{
              /*解决cookie时区问题*/
              expire.setHours(expire.getHours()+8)
              /*设置token存入cookie*/
              res.cookie("token",token,{expires:expire})
              res.json(R.success());
            })
          }
        })
      }else{
        res.json(R.error("该账号已被封禁！"))
      }
    }
  })
})

router.get("/home",function (req,res) {
  res.render("home")
})

router.get("/welcome",function (req,res) {
  res.render("welcome")
})

router.post("/logout",function (req,res) {
  const tid = req.loginInfo.tid;
  const token = md5(uuid.v4());
  let sql = "update user_login set token = ? where id = ?";
  query(sql,[token,tid]).then(r=>{
    res.cookie("token",token,{expires:new Date(-1)})
    res.json(R.success());
  })
})

router.get("/nologin",function (req,res) {
  res.render("nologin");
})

module.exports = router;
